package com.time.store.core.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.time.store.core.entity.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 统一日志处理
 */
@Aspect
@Order(2)
@Component
@Slf4j
public class WebLogAop {


    /**
     * 拦截控制器
     */
    @Pointcut("execution(* com.time.store.*.controller..*.*(..))")
    public void webLog() {
    }


    /**
     * @param joinPoint 切点
     */
    @Before("webLog()")
    public void before(JoinPoint joinPoint) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Object[] args = joinPoint.getArgs();

        List<Object> handleArgs=new ArrayList<>(args.length);
        for (Object arg : args) {
            if (arg == null || arg instanceof HttpServletResponse || arg instanceof HttpServletRequest) {
                continue;
            }
            if (arg instanceof MultipartFile) {
                log.debug("请求参数为文件:" + ((MultipartFile) arg).getOriginalFilename() + " 大小为:" + ((MultipartFile) arg).getSize());
                continue;
            }
            try {
                handleArgs.add(arg);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("请求参数转换json失败");
            }
        }

        log.debug("请求参数为:" + JSON.toJSONString(handleArgs));

    }

    /**
     * @param ret 控制器返回对象
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void afterReturn(Object ret) {
        String requestId = MDC.get("requestId");
        String interval = "";
        if (StringUtils.isNotBlank(requestId)) {
            Long startTime = Long.valueOf(requestId);
            Long endTime = System.currentTimeMillis();
            interval = "处理时间:" + (endTime - startTime) + "ms";
        }
        log.debug(interval + "   响应数据为:" + JSON.toJSONString(ret));
    }
}
